package router

import (
	"io"
	"net/http"

	"github.com/gin-gonic/gin"
)

var (
	globalRouter *gin.Engine // 全局路由总线
)

type RouterConfig struct {
	Enable    bool `mapstructure:"enable" json:"enable" yaml:"enable"`             // 是否开启
	LogEnable bool `mapstructure:"log_enable" json:"log_enable" yaml:"log_enable"` // 是否记录gin日志
	AllowCors bool `mapstructure:"allow_cors" json:"allow_cors" yaml:"allow_cors"` // 是否允许跨域
}

func (rc RouterConfig) Load() {
	if !rc.Enable {
		return
	}
	if rc.LogEnable {
		globalRouter = gin.Default()
	} else {
		globalRouter = gin.New()
	}
	if rc.AllowCors { // 允许跨域
		globalRouter.Use(func(c *gin.Context) {
			//fmt.Printf("接收到跨域请求，url = %#v, method = %s, heads = %#v\n", c.Request.URL, c.Request.Method, c.Request.Header)
			// 如果要加强安全性，可将下面的*号限定为系统内指定的域
			c.Header("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Methods", "*")
			c.Header("Access-Control-Allow-Headers", "*")
			c.Header("Access-Control-Expose-Headers", "*")
			c.Header("Access-Control-Allow-Credentials", "true")
			if c.Request.Method == "OPTIONS" {
				c.AbortWithStatus(http.StatusNoContent)
			}
			c.Next()
		})
	}
}

func SetWriter(w io.Writer) {
	globalRouter.Use(gin.LoggerWithWriter(w), gin.Recovery())
}

func GetRouter() *gin.Engine {
	return globalRouter
}

func GetIRoutes(relativePath string, middleware ...gin.HandlerFunc) gin.IRoutes {
	return GetRouter().Group(relativePath).Use(middleware...)
}
